//
//  Tool.swift
//  ezyform
//
//  Created by FengMoennig on 1/4/16.
//  Copyright © 2016 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import Photos
import Alamofire
import CoreLocation
import CoreGraphics
import YJLocationConverter
import Lottie
func DebugLog<T>(_ message: T, file: String = #file, method: String = #function, line: Int = #line) {
    #if DEBUG
        print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
    #endif
}
open class Tool {
    
    func isValidPwd(pwd:String) -> Bool {
        let regEx = "[A-Z0-9a-z]{6,20}"
        
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: pwd)
    }
    func isValidABN(abn:String) -> Bool {
        let regEx = "[0-9]{11}"
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: abn)
    }
    //MARK: - 0-99.99的正则表达式
    func isValidUnitPrice(_ content : String) -> Bool {
        let regEx = "^[0-9]{1,2}(\\.[0-9]{0,2})?$"////?问号表示小数点后边的小数位可有可无
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: content)
    }
    func isValidPostcode(postcode:String) -> Bool {
        var realCode = postcode
        if postcode.count > 4 {
            realCode = String(postcode.suffix(4))//后边
        }
        let regEx = "[0-9]{4}"
        
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: realCode)
    }
    func isValidPhone(phone:String) -> Bool {
        let regEx = "0[0-9]{9}"
        
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: phone)
    }
    func isValidNMI(nmi:String) -> Bool {
        let regEx = "[0-9]{10,11}"
        
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: nmi)
    }
    func isValidEmail(emailStr:String) -> Bool {
        let regEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: emailStr)
    }
    //MARK: - 长度为length的任意字符
    func isValidLength(content: String, length: Int = 250) -> Bool {
        let regEx = "^.{0,\(length)}"
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: content)
    }
    //MARK: - 检验First name/surname是否有效
    func isValidUserName(content: String) -> Bool {
        let realContent = (content as NSString).replacingOccurrences(of: "\\", with: "\\\\")//反斜杠需要
        let regEx = "^[A-Za-z ./\\-\\\\]{0,\(Constant.MaxTextLength)}"
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: realContent)
    }
    //
    func isValidAddtionalInfo(_ data: String)->Bool{
        let regEx = "^.{7,4000}"
        let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
        return pred.evaluate(with: data)
    }
    func isValidPanelNumber(str:String) -> Bool {
        do {
            let _ = try NSRegularExpression(pattern: APPConfig.PanelNumberRegularExpression, options: NSRegularExpression.Options.caseInsensitive)
        } catch  {//正则表达式不合法
            APPConfig.PanelNumberRegularExpression = "^[0-9a-zA-Z-:|]{5,}$"
        }
        let pred = NSPredicate(format:"SELF MATCHES %@", APPConfig.PanelNumberRegularExpression)
        return pred.evaluate(with: str)
    }
    func isValidInverterNumber(str:String) -> Bool {
        do {
            let _ = try NSRegularExpression(pattern: APPConfig.InverterNumberRegularExpression, options: NSRegularExpression.Options.caseInsensitive)
        } catch  {//正则表达式不合法
            APPConfig.InverterNumberRegularExpression = "^[0-9a-zA-Z-:|]{5,}$"
        }
        let pred = NSPredicate(format:"SELF MATCHES %@", APPConfig.InverterNumberRegularExpression)
        return pred.evaluate(with: str)
    }
    func getScanLicenseAndRegularExpression(){
        //Lincense
        if let data = UserDefaults.standard.object(forKey: "ScanOfflineLicese") as? String{
            APPConfig.ScannerLicense = data
        }
        //confidence
        if let data = UserDefaults.standard.object(forKey: "ScannerConfidence") as? Int{
            APPConfig.ScannerConfidence = data
        }
        //panel regular
        if let data = UserDefaults.standard.object(forKey: "PanelNumberRegularExpression") as? String{
            APPConfig.PanelNumberRegularExpression = data
        }
        //inverter regular
        if let data = UserDefaults.standard.object(forKey: "InverterNumberRegularExpression") as? String{
            APPConfig.InverterNumberRegularExpression = data
        }
        //
        if let data = UserDefaults.standard.object(forKey: "SignatureResendEmailToOwnerInterval") as? Int{
            APPConfig.SignatureResendEmailToOwnerInterval = data
        }
        if let data = UserDefaults.standard.object(forKey: "SignatureResendSMSToOwnerInterval") as? Int{
            APPConfig.SignatureResendSMSToOwnerInterval = data
        }
        if let data = UserDefaults.standard.object(forKey: "ScannerDeblurLevel") as? Int{
            APPConfig.ScannerDeblurLevel = data
        }
        if let data = UserDefaults.standard.object(forKey: "ScannerDeblurConfidence") as? Int{
            APPConfig.ScannerDeblurConfidence = data
        }
        if let data = UserDefaults.standard.object(forKey: "ScannerPanelBrandOrModelForInvertedCode") as? String{
            APPConfig.ScannerPanelBrandOrModelForInvertedCode = data
        }
        if let data = UserDefaults.standard.object(forKey: "ScannerPanelBrandOrModelForFuzzyCode") as? String{
            APPConfig.ScannerPanelBrandOrModelForFuzzyCode = data
        }
        //如果不一样，重新初始化以下license
        ScannerManager.shared.initLicense()
        //2.获取网络设置
        let vm = CommanViewModel()
        vm.setBlockAfterNetwork { (obj, _) in
            if let dic = obj as? NSDictionary, let data = try? JSONSerialization.data(withJSONObject: dic, options: []){
                do{
                    let settingModel = try JSONDecoder().decode(SettingModel.self, from: data)
                    //Dynamsoft扫描license
                    if let data = settingModel.setting?.ios?.license, APPConfig.ScannerLicense != data{
                        UserDefaults.standard.set(data, forKey: "ScanOfflineLicese")
                        APPConfig.ScannerLicense = data
                        //如果不一样，重新初始化以下license
                        ScannerManager.shared.initLicense()
                    }
                    //Dynamsoft扫描信任度
                    if let data = settingModel.setting?.ios?.confidence{
                        UserDefaults.standard.set(data, forKey: "ScannerConfidence")
                        APPConfig.ScannerConfidence = data
                    }
                    //判断panel barcode的正则表达式
                    if let data = settingModel.setting?.ios?.panel_number_regexp{
                        UserDefaults.standard.set(data, forKey: "PanelNumberRegularExpression")
                        APPConfig.PanelNumberRegularExpression = data
                    }
                    //判断inverter barcode的正则表达式
                    if let data = settingModel.setting?.ios?.inverter_number_regexp{
                        UserDefaults.standard.set(data, forKey: "PanelInverterRegularExpression")
                        APPConfig.InverterNumberRegularExpression = data
                    }
                    //给owner重新发送sms的时间间隔（秒）
                    if let data = settingModel.interval_time_phone{
                        UserDefaults.standard.set(data, forKey: "SignatureResendSMSToOwnerInterval")
                        APPConfig.SignatureResendSMSToOwnerInterval = data
                    }
                    //给owner重新发送email的时间间隔（秒）
                    if let data = settingModel.interval_time_email{
                        UserDefaults.standard.set(data, forKey: "SignatureResendEmailToOwnerInterval")
                        APPConfig.SignatureResendEmailToOwnerInterval = data
                    }
                    //deblur lever
                    if let data = settingModel.setting?.ios?.deblur_level{
                        UserDefaults.standard.set(data, forKey: "ScannerDeblurLevel")
                        APPConfig.ScannerDeblurLevel = data
                    }
                    
                    //deblur confidence
                    if let data = settingModel.setting?.ios?.deblur_confidence{
                        UserDefaults.standard.set(data, forKey: "ScannerDeblurConfidence")
                        APPConfig.ScannerDeblurConfidence = data
                    }
                    //auto set invertered scan
                    if let data = settingModel.setting?.ios?.inverted_panel_brand_or_model{
                        UserDefaults.standard.set(data, forKey: "ScannerPanelBrandOrModelForInvertedCode")
                        APPConfig.ScannerPanelBrandOrModelForInvertedCode = data
                    }
                    //auto set fuzzy code setting
                    if let data = settingModel.setting?.ios?.fuzzy_panel_brand_or_model{
                        UserDefaults.standard.set(data, forKey: "ScannerPanelBrandOrModelForFuzzyCode")
                        APPConfig.ScannerPanelBrandOrModelForFuzzyCode = data
                    }
                    UserDefaults.standard.synchronize()
                }catch {
                    DebugLog("转换settingmodel失败")
                }
            }
        } errorBlock: { code, error in
            
        }
        vm.getScanOfflineLicense()
    }
    //判断位置是否在中国
    func isLocationOutOfChina(_ location: CLLocationCoordinate2D)->Bool{
        if (location.longitude < 72.004 || location.longitude > 137.8347 || location.latitude < 0.8293 || location.latitude > 55.8271) {
            return true
        }
        
        return false
        
    }
    func formatFloatStrToCurrency(_ floatStr: String)-> String{
        var convertStr: String = floatStr
        if let range = floatStr.range(of: ".") {
            let tempString = floatStr.prefix(upTo: range.lowerBound)
            convertStr = String(tempString)
        }
        
        //初始化NumberFormatter
        let format = NumberFormatter()
        //设置numberStyle（有多种格式）
        format.numberStyle = .decimal
        //转换后的string
        if let myInteger = Int(convertStr) {
            let myNumber = NSNumber(value:myInteger)
            if let result = format.string(from: myNumber) {
                return result
            }
        }
        return convertStr
        
    }
    //
    //cancel all request for installations
    func cancelAllNetworkRequestForPVD(){
        //取消上传的操作队列
        GlobalOperationQueue.cancelAllOperations()
        //
        netmanagerForUpload.session.getAllTasks { (tasks) in
            tasks.forEach({$0.cancel()})
        }
        //重置upload flag
        DBManager.shared.resetUploadFlag()
    }
    //cancel all request for service job
    func cancelAllNetworkRequestForService(){
        netmanager.session.getAllTasks { (tasks) in
            tasks.forEach({$0.cancel()})
        }
        DBManager.shared.resetServiceUploadFlag()
    }
    //将数字转换为英文表达，例如：12 转换为Twelve
    func convertIntToSpellOut(number: Int) -> String{
        let numberValue = NSNumber(value: number)
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return formatter.string(from: numberValue)!
    }
    
    func getFormatTitle(_ str: String, subStr: String = "",textFont: UIFont, textColor: UIColor )->NSMutableAttributedString{
        let content = subStr + str
        let attrString = NSMutableAttributedString(string: content)
        let attr1: [NSAttributedString.Key : Any] = [.font: textFont as Any,.foregroundColor: textColor]
        let attr2: [NSAttributedString.Key : Any] = [.font: textFont as Any,.foregroundColor: UIColor(red: 0.91, green: 0.26, blue: 0.26,alpha:1)]
        let range = (content as NSString).range(of:subStr )
        attrString.addAttributes(attr1, range: NSRange(location: 0, length: content.count))
        attrString.addAttributes(attr2, range: NSRange(location: range.location, length: range.length))
        return attrString
    }
    
    //字符串转换为保留两位小数且，超过三位数加分号，科学计数法,fabsFlag:表示是否取绝对值
    func formatAmountToStr(amount: String, maximumFractionDigits: Int = 2, minimumFractionDigits: Int = 2)-> String{
        let tempAmount: Double = (amount as NSString).doubleValue
        let numberValue: NSNumber = NSNumber(value: tempAmount)
        let numberFormatter = NumberFormatter()
        numberFormatter.groupingSeparator = ","//三位分割符号
        numberFormatter.groupingSize = 3//每三位分割
        numberFormatter.usesGroupingSeparator = true//开启分割模式
        numberFormatter.decimalSeparator = "."//小数点分割符
        numberFormatter.numberStyle = .decimal//
        numberFormatter.maximumFractionDigits = maximumFractionDigits//小数位最大2位数
        numberFormatter.minimumFractionDigits = minimumFractionDigits//小数位最小2位数
        numberFormatter.roundingMode = .down //截取小数位，不四舍五入
        if let result = numberFormatter.string(from: numberValue) {
            return result
        }
        return amount
    }
    
    //转换经纬度
    func convertCoordinate(_ location: CLLocation)->CLLocation{
        var coordinate = location.coordinate
        if !self.isLocationOutOfChina(location.coordinate) {//在中国经纬度又便宜，要转换下坐标
            coordinate = YJLocationConverter.yj_WGS84Convert(toGCJ02: location.coordinate)
        }
        return CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
    }
    func clearAccountInfo(){
        //1.先清楚登录方式，因为要用APPConfig.loginInfo.email
        LoginMethodServcie().setLoginMethodFlag(.gesture, isOn: false)
        LoginMethodServcie().setLoginMethodFlag(.touchID, isOn: false)
        LoginMethodServcie().setLoginMethodFlag(.faceID, isOn: false)
        LoginMethodServcie().setLoginMethodFlag(.loginMethodGuide, isOn: false)
        UserDefaults.standard.set("" as String, forKey: APPConfig.CachePasswordKey)
        //2.再清除其他
        APPConfig.loginInfo.email = ""
        APPConfig.loginInfo.password = ""
        APPConfig.loginInfo.access_token = ""
        APPConfig.loginInfo.fullName = ""
        APPConfig.loginInfo.accreditedNumber = ""
        UserDefaults.standard.set("" as String, forKey: APPConfig.LoginUserEmailKey)
        UserDefaults.standard.set("" as String, forKey: APPConfig.LoginUserTokenKey)
        UserDefaults.standard.set("" as String, forKey: APPConfig.LoginUserFullNameKey)
    }
    func handleRemoteNotificationForLaunchAPP(){
        if let userInfo = APPConfig.loginInfo.remoteNotification, APPConfig.loginInfo.launchAPPFromNotification {
            APPConfig.loginInfo.launchAPPFromNotification = false
            APPConfig.loginInfo.remoteNotification = nil
            if let window = Tool.getKeyWindow(),let rootVC = window.rootViewController as? TabBarViewController {
                rootVC.messagePushNotification(userInfo)
            }
        }
    }
    func setValueOfUserDefaults(_ value: Any, key: String){
        UserDefaults.standard.set(value, forKey: key)
        UserDefaults.standard.synchronize()
    }
    func getValueOfUserDefaults( key: String)->Any?{
        if let value = UserDefaults.standard.value(forKey: key) {
            return value
        }
        return nil
    }
    func removeOfUserDefaults( key: String){
        UserDefaults.standard.removeObject(forKey: key)
        UserDefaults.standard.synchronize()
    }
    
    func requestCurrentLocation(_ subscrible: GPSSubscription = .single){
        LocationManager.shared.subscription(subscrible).fetchWithCompletion { location, error in
            if let loc = location {
                APPConfig.currentLocation.latitude = "\(loc.coordinate.latitude)"
                APPConfig.currentLocation.longitude = "\(loc.coordinate.longitude)"
                DebugLog("定位返回时间是: \(Date())\n当前线程\(Thread.current)定位信息：\(APPConfig.currentLocation.combineStr)")
            }
        }
    }
    //MARK: - 显示FlushUploadLottieview
    func showFlushUploadLottieView(){
        if let rootVCView = Tool.getRootView(){
            // someJSONFileName 指的就是用 AE 导出的动画 本地 JSON文件名
            let animationView = LottieAnimationView(name: "flushUpload")
            // 可以使用 frame 也可以 使用自动布局
            animationView.loopMode = .loop
            animationView.play()
            rootVCView.addSubview(animationView)
            animationView.snp.makeConstraints { make in
                make.width.height.greaterThanOrEqualTo(0)
                make.center.equalToSuperview()
            }
                
        }
        
    }
    //MARK: - 显示待两个操作按钮的弹框
    func showAlertViewWithOneBtn(title: String = "", message: String, messageTextAlignment: NSTextAlignment = .center,  confirmStr: String = "OK",okClosure: ( () -> Void)? = nil){
        let view = AlertViewWithOneBtn(title: title, message: message, messageTextAlignment: messageTextAlignment, confirmStr: confirmStr,okClosure: okClosure)
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 显示待两个操作按钮的弹框
    func showAlertViewWithTwoBtns(title: String = "", message: String, messageTextAlignment: NSTextAlignment = .center , cancelStr: String = "No", confirmStr: String = "Yes", noClosure: ( () -> Void)? = nil,yesClosure: ( () -> Void)? = nil){
        let view = AlertViewWithTwoBtns(title: title, message: message, messageTextAlignment: messageTextAlignment,cancelStr: cancelStr, confirmStr: confirmStr,yesClosure: yesClosure, noClosure: noClosure)
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 显示Model select弹出视图
    func showSearchModelView(type: SearchModelType, title: String, defaultSearchValue: String = "" ,installDate: String = "",selectClosure: ( (SearchDictionaryModel) -> Void)? = nil){
        let view = SearchModelView(type,title: title, defaultSearchValue: defaultSearchValue,installDate: installDate)
        view.selectClosure = { ( result) in
            selectClosure?(result)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 显示Model select弹出视图
    func showSearchAddressDictionaryView(type: SearchAddressDictionaryType,showPleaseSleectFlag: Bool, title: String, defaultSearchValue: String = "" ,selectClosure: ( (PhysicalAddressViewModel) -> Void)? = nil){
        let view = SearchAddressDictionaryView(type,showPleaseSleectFlag: showPleaseSleectFlag,title: title, defaultSearchValue: defaultSearchValue)
        view.selectClosure = { ( result) in
            guard let result = result else {return}
            selectClosure?(result)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 显示search address 弹出视图
    func showSearchAddressView(defaultSearchValue: String = "" ,selectClosure: ( (PhysicalAddressViewModel) -> Void)? = nil){
        let view = SearchAddressView(defaultSearchValue: defaultSearchValue)
        view.selectClosure = { ( result) in
            selectClosure?(result)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 显示search installer 弹出视图
    func showSearchInstallerView(type: SearchInstallerType, title: String, defaultSearchValue: String = "" ,selectClosure: ( (MyInformationModel) -> Void)? = nil){
        
        let view = CreateJobSearchInstallerView(type,title: title, defaultSearchValue: defaultSearchValue)
        view.selectClosure = { ( result) in
            selectClosure?(result)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 显示search delivery warehouse 弹出视图
    func showSearchDeliveryListView(deliveryWarehouseType: DeliveryWarehouseType ,selectClosure: ( (DeliveryWarehouseModel) -> Void)? = nil){
        let view = SearchDeliveryWarehouseView(deliveryWarehouseType: deliveryWarehouseType)
        view.selectClosure = { ( result) in
            selectClosure?(result)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 登录时显示确认Email的view
    func showConfirmEmailView(_ message: String){
        let view = ConfirmEmailView(conent: message) { msg in
            self.showAlertViewWithOneBtn(message: msg)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //alert failure
    func showFailureInfo(){
        self.showAlertViewWithOneBtn(message: RequestErrorType.NetworkError.rawValue)
    }
    //alert error
    func showErrorInfo(_ code: String = "", _ msg: String,  okClosure: (()->Void)? = nil){
        //请求的Token和server上的token不一致时，强制重新登录
        if code.hasPrefix(APICustomStatusCode.InvalidToken.rawValue) {
            let realMsg = (msg == "" ? R.string.localizable.loginCheckLogged() : msg)
            Tool().showAlertViewWithOneBtn(message: realMsg) {
                LoginService.logOut()
            }
        }else if code.hasPrefix(APICustomStatusCode.ConfireEmailForLogin.rawValue){//新账号或邮箱账号修改，登录时确认是否点击确认邮件
            Tool().showConfirmEmailView(msg)
            
        }else if code.hasPrefix(APICustomStatusCode.ForceUpdate.rawValue){//API提示强制更新
            Tool().forceUpgradeFromAppStore(message: msg)
            
        }else if code.hasPrefix(APPConfig.ShowErrorInfoUpgradePrefix){//旧的强制更新
            Tool().forceUpgradeFromAppStore(message: msg)
            
        }else if code.hasPrefix(APICustomStatusCode.InvalidParamsForUploadSignature.rawValue){
            Tool().showAlertViewWithOneBtn(message:msg){
                okClosure?()
            }
        }else if code == APICustomStatusCode.JobNotFound.rawValue {//如果没有找到这个job，要返回到list（installation list，calendar，service jobs界面）
            Tool().showAlertViewWithOneBtn(message: msg){
                if let navi = self.getCurrentNaviViewController(){//获取当前的navi controller
                    for vc in navi.viewControllers{
                        if let listVC = vc as? JobsListViewController{//installations
                            listVC.loadData(loadingFlag: false)
                            navi.popToViewController(listVC, animated: true)
                        }else if let listVC = vc as? CalendarViewController{//calendar
                            listVC.loadAllData(loadWeatherFlag: true, loadJobsListPerDayFlag: true,loadingFlag: false)
                            navi.popToViewController(vc, animated: true)
                        }else if let listVC = vc as? ServiceJobsViewController{//service jobs
                            listVC.loadData(loadingFlag: false)
                            navi.popToViewController(vc, animated: true)
                        }
                    }
                }
                okClosure?()
            }
        }else {
            let alertMsg = (msg == "" ? RequestErrorType.NetworkError.rawValue : msg)
            Tool().showAlertViewWithOneBtn(message: alertMsg){
                okClosure?()
            }
        }
    }
    //MARK: - 将post参数转换为json 字符串
    func printPostJSONString(_ params: Parameters){
        var result:String = ""
        if APPConfig.isTestFlag {
            //获取Post字符串
            do {
                //如果设置options为JSONSerialization.WritingOptions.prettyPrinted，则打印格式更好阅读
                let jsonData = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.init(rawValue: 0))
                
                if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                    result = JSONString
                }
                
            } catch {
                result = ""
            }
            print(result.jsonFormatPrint())
        }
    }
    //MARK: - 强制升级APP
    func forceUpgradeFromAppStore(title: String = "", message: String){
        self.showAlertViewWithOneBtn(title: title, message: message, messageTextAlignment: .left, confirmStr: R.string.localizable.upgradeNow()) {
            //点击Update Now 后不关闭弹窗，防止客户跳转后不升级又返回app继续操作了
            self.toAppStoreUpgrade()
        }
    }
    //MARK: - 非强制升级APP，有新版本就提示
    func upgradeFromAppStore(title: String = "", message: String){
        self.showAlertViewWithTwoBtns(title: title, message: message, messageTextAlignment: .left,cancelStr: R.string.localizable.laterOn(), confirmStr: R.string.localizable.upgradeNow(), noClosure: nil) {
            self.toAppStoreUpgrade()
        }
    }
    //MARK: - 跳转到app store
    private func toAppStoreUpgrade(){
        if let url = URL(string: APIConfig.AppUpgradeAPI) {
            if UIApplication.shared.canOpenURL(url){
                UIApplication.shared.open(url, options: [:],completionHandler: nil)
            }
        }
    }
    static func getKeyWindow()->UIWindow?{
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate,let window = appDelegate.window{//必须用这行代码，因为启动app完成前已经在使用window变量了，此时换没有执行到window?.makeKeyAndVisible(),所以UIApplication.shared.windows.filter({$0.isKeyWindow}).first的代码换是空
            return window
        }
        return nil
    }
    //
    static func getRootView()->UIView?{
        guard let window = Tool.getKeyWindow() else {return nil}
        guard let rootVCView = window.rootViewController?.view else{ return nil}
        //如果当前controller是被present出来的，弹框都要加载当前页面上
        if let presentedVC = Tool.getPresentedViewController(){
            return presentedVC.view
        }
        return rootVCView
    }
    //MARK: 获取当前的present出来的viewcontroller。
    class private func getPresentedViewController()->UIViewController?{
        guard let window = Tool.getKeyWindow() else {return nil}
        guard let rootVC = window.rootViewController else{ return nil}
        var topVC: UIViewController?
        if rootVC.presentedViewController != nil {
            topVC = rootVC.presentedViewController
        }
        return topVC
    }
    //Mark: - 获取当前正在显示的View controller的View
//    class private func getCurrentView() -> UIView?{
//        guard let window = Tool.getKeyWindow(),let rootVc = window.rootViewController else {return nil}
//        let currentVc = getCurrentVcFrom(rootVc)
//        return currentVc.view
//    }
    class private func getCurrentVcFrom(_ rootVc: UIViewController) -> UIViewController{
        var currentVc:UIViewController
        var rootCtr = rootVc
        if(rootCtr.presentedViewController != nil) {
            rootCtr = rootVc.presentedViewController!
        }
        if rootVc.isKind(of:UITabBarController.classForCoder()) {
            currentVc = getCurrentVcFrom((rootVc as! UITabBarController).selectedViewController!)
        }else if rootVc.isKind(of:UINavigationController.classForCoder()){
            currentVc = getCurrentVcFrom((rootVc as! UINavigationController).visibleViewController!)
        }else{
            currentVc = rootCtr
        }
        return currentVc
    }
    //获取当前的 controller
    class func getCurrentViewController() -> UIViewController?{
        guard let window = Tool.getKeyWindow(),let rootVc = window.rootViewController else {return nil}
        return Tool.getCurrentVcFrom(rootVc)
    }
    //获取当前的navi view controller
    private func getCurrentNaviViewController() -> BaseNavigationController?{
        guard let window = Tool.getKeyWindow(),let tabBarVC = window.rootViewController as? TabBarViewController,let vcs = tabBarVC.viewControllers else {return nil}
        if let navi = vcs[tabBarVC.selectedIndex] as? BaseNavigationController{
            return navi
        }
        return nil
    }
}

